import { reactive } from "vue";
import { defineStore } from "pinia";
import pinia from "./defaultPinia";
import { useUserStore } from "./userStore";
import api from "@/api";
import { routers } from "@/router";

export const usePermissionStore = defineStore("permission", () => {
  const permission = reactive({
    menuList: [],
  });

  function setMenuList(data) {
    permission.menuList = data;
  }

  function getMenuList() {
    return permission.menuList;
  }

  async function setMenuListAction() {
    const userStore = useUserStore(pinia);
    if (userStore.getUserInfo().isAdmin) {
      permission.menuList = routers;
    } else {
      const permissionRes = await api.auth.getMenuList({}).catch((err) => {
        console.log(err);
      });
      if (permissionRes?.data?.menuList?.length) {
        permission.menuList = permissionRes.data.menuList;
      } else {
        permission.menuList = [];
      }
    }
  }

  return { permission, setMenuList, setMenuListAction, getMenuList };
});
